import { login, logout, getInfo } from '@/api/acl/user'
import{resetRouter,constantRoutes,allAsyncRoutes,anyRoute} from '@/router/index'
import   router from '@/router'
import cloneDeep from 'lodash/cloneDeep'

function filterAsyncRoutes(allAsyncRoutes,routeNames){
    let asyncRoutes = allAsyncRoutes.filter(item=>{
        if(routeNames.indexOf(item.name)  !== -1){
           if(item.children && item.children.length){
             item.children = filterAsyncRoutes(item.children,routeNames)
           }
           return true
        }
    })
    return  asyncRoutes
}

const state = {
  // token:'',
  token:localStorage.getItem('token_key'),
  name: '',
  avatar: '',

  buttons:[],
  roles:[], 
  // asyncRoutes:[], //放过滤完的所有用户的路由数组
  routes:[], //侧边栏遍历时候使用  //放请求返回的routes,内部是：路由的name字符串组成的，后面从这个里面过滤出来当前用户想要的动态路由
}

const mutations = {
  //重置用户信息
  RESET_STATE: (state) => {
    state.token= '',
    state.name='',
    state.avatar= ''

    state.buttons =[]
    state.roles=[]
    state.routes=[]
  },
  //接收token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  //接收用户信息（name，avatar）
   SET_USERINFO(state,userInfo){
    state.name = userInfo.name
    state.avatar = userInfo.avatar

    state.buttons =userInfo.buttons
    state.roles=userInfo.roles
   },
   SET_ROUTES(state,asyncRoutes){
      // state.asyncRoutes = asyncRoutes

      //保存所有的路由组成的数组,用于让形成侧边栏菜单的时候，遍历使用的
      state.routes = constantRoutes.concat(asyncRoutes,anyRoute)

      // 还要把动态路由和任意路由，动态添加到路由器的配置项当中,形成一个完整的路由配置数组
      router.addRoutes([...asyncRoutes,anyRoute])
   }
}

const actions = {
  
  //登录
   async  login({commit},{ username, password }){
      const result = await login({ username, password })
      if( result.code === 200 || result.code === 20000){
         commit('SET_TOKEN',result.data.token)
         localStorage.setItem('token_key',result.data.token)
         return 'ok'
      }else{
         return Promise.reject(new Error('failed'))
      }
   },
   

    //根据token获取用户信息
    async  getInfo({commit,state}){
       const result = await getInfo(state.token)
       if(result.code === 200 ||  result.code === 20000){
          commit('SET_USERINFO',result.data)


        //result.data.routes,这个是所有路由name字符串组成的字符串数组，不是都要，需要过滤  
        // commit('SET_ROUTES',过滤后的数组)  
        commit('SET_ROUTES',filterAsyncRoutes(cloneDeep(allAsyncRoutes),result.data.routes))

          return 'ok'
       }else{
          return Promise.reject(new Error('failed'))
       }
    },


  
  //退出登录
   async logout({commit,state,dispatch}){
        const result = await  logout(state.token)
        if(result.code === 200 || result.code === 20000){
          resetRouter()

          dispatch('resetToken')
          return 'ok'
        }else{
           return Promise.reject(new Error('failed'))
        }
   },

  // 重置用户信息
    async resetToken({commit}){
      localStorage.removeItem('token_key')
      commit('RESET_STATE')
    }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

